import {Injectable} from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import {mergeMap, Observable, of} from 'rxjs';
import {UserService} from "../service/user.service";

@Injectable()
export class JwtInterceptor implements HttpInterceptor {

  constructor(private userService: UserService) {
  }

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    let req = this.prepareRequest(request)
    return next.handle(req).pipe(
      mergeMap(event => {
        return of(event)
      })
    );
  }

  prepareRequest(req: HttpRequest<unknown>): HttpRequest<unknown> {
    const jwt = this.userService.getJwt()
    if (jwt == null) {
      return req.clone()
    } else {
      return req.clone({
        setHeaders: {
          "Authorization": jwt
        }
      })
    }
  }
}
